import 'package:flutter/material.dart';
import 'package:fsharing/core/models/message.dart';
import 'package:fsharing/core/viewmodels/pages/message/message_query_model.dart';
import 'package:fsharing/core/viewmodels/pages/message/message_view_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MessagePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => MessageQueryModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => MessageViewModel(Provider.of(context, listen: false)),
        ),
      ],
      child: Consumer<MessageQueryModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget();
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    MessageQueryModel model = Provider.of(context, listen: false);
    List<Message> list = model.list;
    List<Message> messages = model.messages;
    return Scaffold(
      appBar: AppBar(
        title: Text('消息'),
      ),
      body: SmartRefresher(
        controller: _refreshController,
        child: ListView.separated(
          padding: EdgeInsets.symmetric(horizontal: 12),
          itemBuilder: (context, index) {
            return _MessageItemWidget(
              message: list[index],
            );
          },
          separatorBuilder: (context, index) {
            return Divider(
              height: 12,
              color: Colors.transparent,
            );
          },
          itemCount: list.length,
        ),
        enablePullDown: false,
        enablePullUp: messages.length == 10,
        onLoading: () {
          _onLoadData(context);
        },
      ),
    );
  }

  void _onLoadData(BuildContext context) async {
    MessageQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _MessageItemWidget extends StatelessWidget {
  final Message message;

  const _MessageItemWidget({
    Key key,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Column(
        children: <Widget>[
          _MessageHeaderWidget(message: message),
          Theme(
            data: lightTheme(),
            child: Material(
              borderRadius: BorderRadius.vertical(
                bottom: Radius.circular(8),
              ),
              child: Container(
                padding: EdgeInsets.all(12),
                child: Column(
                  children: <Widget>[
                    Text(message.message),
                    Container(
                      margin: EdgeInsets.only(top: 8),
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            child: Text(
                              message.msgTypeName,
                              style: TextStyle(color: Colors.grey, fontSize: 13),
                            ),
                          ),
                          if (message.enableSm)
                            Text(
                              message.send ? '已发短信' : '未发短信',
                              style: TextStyle(color: Colors.grey, fontSize: 13),
                            ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          )
        ],
      ),
      onTap: message.viewed
          ? null
          : () {
              _onItemClicked(context);
            },
    );
  }

  void _onItemClicked(BuildContext context) async {
    MessageViewModel model = Provider.of(context, listen: false);
    var viewState = await model.messageView(message.id);
    switch (viewState) {
      case ViewState.busy:
        break;
      default:
        showToast('已阅');
        MessageQueryModel messageQueryModel = Provider.of(context, listen: false);
        messageQueryModel.refreshData();
        break;
    }
  }
}

class _MessageHeaderWidget extends StatelessWidget {
  final Message message;

  const _MessageHeaderWidget({
    Key key,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text(
              message.createTime,
              style: TextStyle(fontSize: 14),
            ),
          ),
          Text(message.viewed ? '已阅' : '未阅')
        ],
      ),
    );
  }
}
